package com.hp.team.bookstore.dbaccess.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * https://community.jboss.org/wiki/GenericDataAccessObjects
 * 
 * @param <T>
 * @param <ID>
 */
public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {

	private Class<T> persistentClass;

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public GenericHibernateDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	@SuppressWarnings("unchecked")
	public T findById(ID id, boolean lock) {
		T entity;

		if (lock)
			entity = (T) getSession().get(getPersistentClass(), id, LockOptions.UPGRADE);
		else
			entity = (T) getSession().get(getPersistentClass(), id);

		return entity;
	}

	@Override
	public List<T> findAll() {
		return findByCriteria();
	}

	@Override
	public List<T> findByExample(T exampleInstance, String... excludeProperty) {
//		Example example = Example.create(exampleInstance);
//
//		for (String exclude : excludeProperty) {
//			example.excludeProperty(exclude);
//		}
		
		Example example = getExample(exampleInstance, excludeProperty);
		return findByCriteria(example);
	}

	@Override
	public T makePersistent(T entity) {
		getSession().saveOrUpdate(entity);
		return entity;
	}

	@Override
	public void makeTransient(T entity) {
		getSession().delete(entity);
	}

	@Override
	public Long count() {
		return (Long) getSession().createCriteria(getPersistentClass()).setProjection(Projections.rowCount())
				.uniqueResult();

	}

	public void flush() {
		getSession().flush();
	}

	public void clear() {
		getSession().clear();
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criteria) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criteria) {
			crit.add(c);
		}
		return crit.list();
	}

	protected Example getExample(T exampleInstance, String... excludeProperty) {
		Example example = Example.create(exampleInstance);

		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}

		return example.excludeZeroes();
	}

}
